package com.larry.isn;

import java.util.List;

import com.pegatron.ers.server.app.service.common.IProductService;
import com.pegatron.ers.util.LogUtil;
import com.pegatron.ers.vo.product.ProductConfig;

public class WebServiceSearcher extends Thread {

	private Long tmpTimeLog = 0L;

	private Integer i = 1;

	private Integer perDayUnits;

	private Recorder recorder;

	private List<String> list;

	private IProductService pService;

	private ProductConfig config;

	public WebServiceSearcher(Integer perDayUnits, Recorder recorder, List<String> list, IProductService pService, ProductConfig config) {
		this.perDayUnits = perDayUnits;
		this.recorder = recorder;
		this.list = list;
		this.pService = pService;
		this.config = config;
	}

	@Override
	public void run() {
		for (String serialNr : list) {
			if (i.compareTo(perDayUnits) > 0) {
				Thread.currentThread().interrupt();
				return;
			}
			recorder.runSum();
			this.multiRun(serialNr);
			i++;
		}
	}

	private void multiRun(String serialNr) {
		try {
			if (!recorder.isAllowToNextTurn()) {
				LogUtil.info(this.getClass(), "Total size:" + i + ", Runner size:" + recorder.getRunSum() + ", Callback size:" + recorder.getCallBackSum());
//				if (!this.validateWaitingStatus()) {
//					recorder.init();
//				}
				Thread.sleep(5000);
				this.multiRun(serialNr);
			}
			tmpTimeLog = System.currentTimeMillis();
			IsnRunner runner = new IsnRunner(serialNr, pService, config, recorder);
			runner.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private Boolean validateWaitingStatus() {
		Long currTime = System.currentTimeMillis();
		if (currTime - tmpTimeLog > 60000) {
			return false;
		}
		return true;
	}
}
